import { useState } from 'react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { useContactInfo } from '@/hooks/useCompany';
import { useCreateMessage } from '@/hooks/useMessages';
import { ContactInfo } from '@/types';

// 默认联系信息（作为后备）
const defaultContact: ContactInfo = {
  phone: '020-12345678',
  email: 'info@gzlfhjgc.com',
  address: '广东省广州市天河区珠江新城华夏路88号',
  website: 'www.gzlfhjgc.com'
};

export default function ContactSection() {
  // 获取联系信息
  const { data: contactInfo, isLoading, error } = useContactInfo();
  const createMessage = useCreateMessage();

  // 表单状态
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    email: '',
    subject: '',
    message: ''
  });

  // 使用API数据或默认数据
  const contact = contactInfo || defaultContact;

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 验证必填字段
    if (!formData.name || !formData.phone || !formData.message) {
      toast.error('请填写所有必填字段');
      return;
    }

    try {
      await createMessage.mutateAsync({
        name: formData.name,
        phone: formData.phone,
        email: formData.email || undefined,
        subject: formData.subject || undefined,
        message: formData.message
      });

      // 重置表单
      setFormData({
        name: '',
        phone: '',
        email: '',
        subject: '',
        message: ''
      });

      toast.success('留言提交成功，我们会尽快与您联系！');
    } catch (error) {
      console.error('提交留言失败:', error);
      toast.error('提交失败，请重试');
    }
  };

  return (
    <section id="contact" className="py-20">
      <div className="container mx-auto px-4">
        <div className="text-center mb-16">
          <h2 className="text-3xl md:text-4xl font-bold text-gray-800 mb-4">联系我们</h2>
          <div className="w-20 h-1 bg-blue-600 mx-auto"></div>
        </div>

        <div className="grid md:grid-cols-2 gap-12">
          <div>
            <div className="bg-white p-8 rounded-lg shadow-md border border-gray-100 h-full">
              <h3 className="text-2xl font-semibold text-gray-800 mb-6">联系方式</h3>

              {/* 加载状态 */}
              {isLoading && (
                <div className="flex justify-center items-center py-8">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                  <span className="ml-2 text-gray-600">加载联系信息...</span>
                </div>
              )}

              {/* 错误状态 */}
              {error && !isLoading && (
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
                  <p className="text-yellow-600 text-sm">无法加载最新联系信息，显示默认信息</p>
                </div>
              )}

              {/* 联系信息 */}
              {!isLoading && (
                <div className="space-y-6">
                  {contact.address && (
                    <div className="flex items-start">
                      <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-4 flex-shrink-0 text-blue-600">
                        <i className="fa-solid fa-map-marker-alt"></i>
                      </div>
                      <div>
                        <h4 className="text-lg font-medium text-gray-800 mb-1">公司地址</h4>
                        <p className="text-gray-600">{contact.address}</p>
                      </div>
                    </div>
                  )}

                  {contact.phone && (
                    <div className="flex items-start">
                      <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-4 flex-shrink-0 text-blue-600">
                        <i className="fa-solid fa-phone"></i>
                      </div>
                      <div>
                        <h4 className="text-lg font-medium text-gray-800 mb-1">联系电话</h4>
                        <p className="text-gray-600">
                          <a href={`tel:${contact.phone}`} className="hover:text-blue-600 transition-colors">
                            {contact.phone}
                          </a>
                        </p>
                      </div>
                    </div>
                  )}

                  {contact.email && (
                    <div className="flex items-start">
                      <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-4 flex-shrink-0 text-blue-600">
                        <i className="fa-solid fa-envelope"></i>
                      </div>
                      <div>
                        <h4 className="text-lg font-medium text-gray-800 mb-1">电子邮箱</h4>
                        <p className="text-gray-600">
                          <a href={`mailto:${contact.email}`} className="hover:text-blue-600 transition-colors">
                            {contact.email}
                          </a>
                        </p>
                      </div>
                    </div>
                  )}

                  {contact.website && (
                    <div className="flex items-start">
                      <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-4 flex-shrink-0 text-blue-600">
                        <i className="fa-solid fa-globe"></i>
                      </div>
                      <div>
                        <h4 className="text-lg font-medium text-gray-800 mb-1">官方网站</h4>
                        <p className="text-gray-600">
                          <a
                            href={contact.website.startsWith('http') ? contact.website : `https://${contact.website}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="hover:text-blue-600 transition-colors"
                          >
                            {contact.website}
                          </a>
                        </p>
                      </div>
                    </div>
                  )}

                  <div className="flex items-start">
                    <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mr-4 flex-shrink-0 text-blue-600">
                      <i className="fa-solid fa-clock"></i>
                    </div>
                    <div>
                      <h4 className="text-lg font-medium text-gray-800 mb-1">工作时间</h4>
                      <p className="text-gray-600">周一至周五: 9:00 - 18:00</p>
                      <p className="text-gray-600">周六至周日: 休息</p>
                    </div>
                  </div>
                </div>
              )}
              
              <div className="mt-8">
                <h4 className="text-lg font-medium text-gray-800 mb-4">关注我们</h4>
                <div className="flex space-x-4">
                  <a
                    href="#"
                    title="关注我们的微信"
                    aria-label="关注我们的微信"
                    className="w-10 h-10 bg-blue-600 hover:bg-blue-700 text-white rounded-full flex items-center justify-center transition-colors"
                  >
                    <i className="fa-brands fa-weixin"></i>
                  </a>
                  <a
                    href="#"
                    title="关注我们的微博"
                    aria-label="关注我们的微博"
                    className="w-10 h-10 bg-blue-400 hover:bg-blue-500 text-white rounded-full flex items-center justify-center transition-colors"
                  >
                    <i className="fa-brands fa-weibo"></i>
                  </a>
                  <a
                    href="#"
                    title="关注我们的LinkedIn"
                    aria-label="关注我们的LinkedIn"
                    className="w-10 h-10 bg-gray-800 hover:bg-gray-900 text-white rounded-full flex items-center justify-center transition-colors"
                  >
                    <i className="fa-brands fa-linkedin"></i>
                  </a>
                </div>
              </div>
            </div>
          </div>

          <div>
            <div className="bg-white p-8 rounded-lg shadow-md border border-gray-100 h-full">
              <h3 className="text-2xl font-semibold text-gray-800 mb-6">留言咨询</h3>

              <form onSubmit={handleSubmit}>
                <div className="grid md:grid-cols-2 gap-6 mb-6">
                  <div>
                    <label htmlFor="name" className="block text-gray-700 font-medium mb-2">
                      姓名 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="name"
                      name="name"
                      value={formData.name}
                      onChange={handleInputChange}
                      required
                      className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入您的姓名"
                    />
                  </div>
                  <div>
                    <label htmlFor="phone" className="block text-gray-700 font-medium mb-2">
                      电话 <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      value={formData.phone}
                      onChange={handleInputChange}
                      required
                      className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                      placeholder="请输入您的电话"
                    />
                  </div>
                </div>

                <div className="mb-6">
                  <label htmlFor="email" className="block text-gray-700 font-medium mb-2">邮箱</label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入您的邮箱"
                  />
                </div>

                <div className="mb-6">
                  <label htmlFor="subject" className="block text-gray-700 font-medium mb-2">主题</label>
                  <select
                    id="subject"
                    name="subject"
                    value={formData.subject}
                    onChange={handleInputChange}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  >
                    <option value="">请选择咨询主题</option>
                    <option value="项目合作咨询">项目合作咨询</option>
                    <option value="服务内容咨询">服务内容咨询</option>
                    <option value="环境影响评价">环境影响评价</option>
                    <option value="污染治理工程">污染治理工程</option>
                    <option value="环境监测检测">环境监测检测</option>
                    <option value="招聘信息咨询">招聘信息咨询</option>
                    <option value="其他问题">其他问题</option>
                  </select>
                </div>

                <div className="mb-6">
                  <label htmlFor="message" className="block text-gray-700 font-medium mb-2">
                    留言内容 <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    id="message"
                    name="message"
                    value={formData.message}
                    onChange={handleInputChange}
                    rows={5}
                    required
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors resize-none"
                    placeholder="请详细描述您的需求或问题，我们会尽快为您提供专业的解答"
                  ></textarea>
                </div>

                <button
                  type="submit"
                  disabled={createMessage.isPending}
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors transform hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
                >
                  {createMessage.isPending ? '提交中...' : '提交留言'}
                </button>

                <p className="text-sm text-gray-500 mt-4 text-center">
                  我们承诺保护您的隐私信息，仅用于业务咨询回复
                </p>
              </form>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}